import os
import ctypes
import logging

# "SLAVE_NAME": ("Product_ID", "SLAVE_length", CHECK_METHOD)
SLAVE_MAPPING = {
    "PLC32": (0x1116, 4),
    "PLC48": (0x1113, 6),
    "PANEL": (0x1112, 8),
    "IAPEC": (0x1150, 6),
}

# 需要实现单例模式 ??
class SlaveList:
    def __init__(self, path_lib_ioslave):
        self.lib_ioslave = ctypes.CDLL(path_lib_ioslave)
        self.lib_ioslave.slave_initialize()

        # "SLAVE_NAME": ("Product_ID", CHECK_METHOD)
        self.slave_mapping = {}
        for slave_name in SLAVE_MAPPING.keys():
            if slave_name == "IAPEC":
                CHECK_METHOD = self.lib_ioslave.whether_iapec_slave
            else:
                CHECK_METHOD = self.lib_ioslave.whether_normal_slave
            self.slave_mapping[slave_name] = CHECK_METHOD

    def get_slave_size(self):
        return self.lib_ioslave.get_slave_size()

    def check_slave_type(self, index):
        for slave_name, CHECK_METHOD in self.slave_mapping.items():
            Product_ID = SLAVE_MAPPING[slave_name][0]
            if CHECK_METHOD(index, Product_ID):
                return slave_name
        raise Exception("无法验证类型的板卡，请查证！")

    def get_slave_list(self):
        """ return a list of [("SLAVE_NAME", SLAVE_LENGTH), ... ] """
        list_ret = []
        for index in range(self.get_slave_size()):
            slave_name = self.check_slave_type(index)
            slave_length = SLAVE_MAPPING[slave_name][1]
            logging.debug("SlaveList::get_slave_list() -->> {}: {}".format(slave_name, self.slave_mapping[slave_name]))
            list_ret.append((slave_name, slave_length))
        return list_ret


if __name__ == "__main__":
    list_slave = SlaveList("./libioslave.so")
    list_slave.get_slave_list()
